package com.android.lovely.ui.activity

import android.Manifest
import android.app.Activity
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.android.lovely.R
import com.android.lovely.api.UnlockCardUseCase
import com.android.lovely.const.CardUL
import com.android.lovely.data.CardItem
import com.android.lovely.databinding.ActivityBigCardBinding
import com.android.lovely.databinding.ItemBigCardBinding
import com.android.lovely.ext.downloadImage
import com.android.lovely.ext.fullScreen
import com.android.lovely.ext.loadBlurredImage
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.manager.KVStore
import com.android.lovely.room.BotCacheService
import com.android.lovely.room.BotCacheService.observeBot
import com.android.lovely.ui.chat.ChatMessageActivity
import com.android.lovely.ui.dialog.showLovelyDialog
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.context.ContextExt.startPageClearTop
import com.kotlin.extensions.coroutine.CoroutineExt.doOnIO
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest

/**
 *
 * @author why
 * @date 2025/3/24 20:09
 */
class BigCardActivity : BaseActivity<ActivityBigCardBinding>() {

    private val pictures = arrayListOf<CardItem>()

    private val adapter by lazy { BigCardAdapter() }

    private val launcher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                lifecycleScope.launchSafety {
                    val currentItem = mBinding.vp.currentItem
                    // 检查当前位置是否在有效范围内
                    if (currentItem >= 0 && currentItem < adapter.itemCount) {
                        val item = adapter.getItems().get(currentItem)
                        download(item)
                    }
                }
            }
        }
    override fun initView(savedInstanceState: Bundle?) {
        fullScreen()
        mBinding.llTop.addStatusBarMarginTop()
        mBinding.ivLeft.clickable {
            finish()
        }
        val list = intent.getParcelableArrayListExtra<CardItem>("cards").orEmpty()
        pictures.addAll(list)
        val position = intent.getIntExtra("position", 0)
        val id = intent.getIntExtra("botId", 0)
        val name = intent.getStringExtra("name")

        if(!KVStore.isFirstShowBigCardGuide) {
            KVStore.isFirstShowBigCardGuide = true
            mBinding.guide.isVisible = true
        } else {
            mBinding.guide.isVisible = false
        }

        adapter.onItemClick = onItemClick@{ item, position ->
            item?: return@onItemClick
            if (!item.isUnlock) {
                showUnlockDialog(id, item) { id,item ->
                    BotCacheService.updateBot(id) {
                        background = item.cardUrl
                    }
                }
            }

        }

        mBinding.vp.adapter = adapter
        mBinding.vp.offscreenPageLimit = 2
        adapter.updateList(pictures)

        mBinding.vp.setCurrentItem(position, false)

        mBinding.tvTitle.text = name
        lifecycleScope.observeBot(id) {
            val name = it?.name ?: return@observeBot
            mBinding.tvTitle.text = name
        }
        lifecycleScope.launchSafety {
            FlowBus.flowOf<CardUL>().collectLatest {
                it.ids.forEach { cardId ->
                    adapter.getItems().forEach { picture ->
                        if (picture.id == cardId) {
                            picture.isUnlock = true
                        }
                    }
                }
                adapter.notifyItemRangeChanged(0, adapter.itemCount)
            }
        }
        mBinding.report.clickable {
            startPage<OptimizationActivity>("user_id" to id)
        }
        mBinding.save.clickable {
            val currentItem = mBinding.vp.currentItem
            if (currentItem >= 0 && currentItem < adapter.itemCount) {
                val item = adapter.getItems().get(currentItem)
                if (!item.isUnlock) {
                    showUnlockDialog(id, item) {id,item ->
                        download(item)
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        download(item)
                    }  else {
                        launcher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    }
                }
            }
        }
        mBinding.chat.clickable {
            val currentItem = mBinding.vp.currentItem
            if (currentItem >= 0 && currentItem < adapter.itemCount) {
                val item = adapter.getItems().get(currentItem)
                if (!item.isUnlock) {
                    showUnlockDialog(id, item) { id,item ->
                        BotCacheService.updateBot(id) {
                            background = item.cardUrl
                        }
                        startPageClearTop<ChatMessageActivity>("id" to id)
                    }
                } else {
                    startPageClearTop<ChatMessageActivity>("id" to id)
                }
            }
        }
    }

    private fun showUnlockDialog(botId: Int, item: CardItem, onNext : (Int, CardItem) -> Unit) {
        showLovelyDialog {
            setDialogTitle(getString(R.string.unlock_title))
            setDialogMessage(getString(R.string.unlock_message))
            setPositiveButton {
                lifecycleScope.launchSafety {
                    showLoading()
                    UnlockCardUseCase.execute(botId, item.id)
                    onNext.invoke(botId, item)
                    dismissLoading()
                }.onError {
                    dismissLoading()
                }
            }
        }
    }

    private fun download(picture: CardItem) {
        lifecycleScope.launchWithLoading {
            doOnIO{
                downloadImage(picture.cardUrl).fold(
                    onSuccess = {
                        // 下载成功
                        showToast(getString(R.string.download_successfully))
                    },
                    onFailure = { e ->
                        // 处理错误
                        showToast(getString(R.string.download_image_failed))
                    }
                )
            }
        }
    }

    companion object {
        fun start(
            activity: Activity,
            botId: Int,
            position: Int,
            name: String,
            cards: List<CardItem>
        ) {
            activity.startPage<BigCardActivity>(
                "botId" to botId,
                "name" to name,
                "position" to position,
                "cards" to cards
            )
        }
    }
}

class BigCardAdapter() :
    BaseAdapter<CardItem, ItemBigCardBinding>() {
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: CardItem?,
        binding: ItemBigCardBinding,
        position: Int
    ) {
        val item = item ?: return
        holder.binding.apply {
            clLock.isVisible = item.isUnlock.not()
            if (item.isUnlock) {
                ivImage.loadWithPlaceholder(item.cardUrl)
            } else {
                ivImage.loadBlurredImage(item.cardUrl)
            }
            tvCollect.text = item.intimacyValue.toString()
            tvDiamond.text = item.point.toString()
            tvCollect.isVisible = item.intimacyValue > 0
            tvDiamond.isVisible = item.point > 0
            tvOr.isVisible = item.intimacyValue > 0 && item.point > 0
            ivImage.setOnViewTapListener { view, fl, fl2 ->
                onItemClick?.invoke(item, position)
            }

        }
    }
}
